<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!--      <el-form-item label="序列号" prop="serialNo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.serialNo"-->
      <!--          placeholder="请输入序列号"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--          class="!w-240px"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="产线" prop="lineId">
        <el-select v-model="queryParams.lineId" class="!w-160px" clearable placeholder="请选择产线">
          <el-option
            v-for="item in productLineList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="设备" prop="equipment">
        <el-select
          v-model="queryParams.equipment"
          class="!w-160px"
          clearable
          placeholder="请选择设备"
        >
          <el-option v-for="item in deviceList" :key="item.equipment" :label="item.equipmentName" :value="item.equipment" />
        </el-select>
      </el-form-item>

      <el-form-item label="工序" prop="process">
        <el-select
          v-model="queryParams.process"
          class="!w-160px"
          clearable
          disabled
        >
          <el-option v-for="item in processList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>

      <!--      <el-form-item>-->
      <!--        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>-->
      <!--        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          @click="openForm('create')"-->
      <!--          v-hasPermi="['opticore:work-report:create']"-->
      <!--        >-->
      <!--          <Icon icon="ep:plus" class="mr-5px" /> 新增-->
      <!--        </el-button>-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          @click="handleExport"-->
      <!--          :loading="exportLoading"-->
      <!--          v-hasPermi="['opticore:work-report:export']"-->
      <!--        >-->
      <!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
      <!--        </el-button>-->
      <!--      </el-form-item>-->
    </el-form>
<!--   这里设置一个切换开关  当前页面是报工  切换成开工 下面就是开工按钮   -->
    <div class="serial-number"></div>
    <div class="report-btn-container">
      <el-radio-group v-model="mode" style="margin-bottom: 20px;">
        <el-radio-button label="report">报工</el-radio-button>
        <el-radio-button label="start">开工</el-radio-button>
      </el-radio-group>
    </div>

    <div class="serial-number">
      <el-input v-model="serial" class="serial-input" placeholder="请扫描物料序列号" clearable>
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
    </div>

    <div class="report-btn-container">
      <div v-if="mode === 'report'">
        <el-button type="primary" class="report-btn" @click="handleReport">报工</el-button>
      </div>
      <div v-else>
        <el-button type="primary" class="report-btn" @click="handleStart">开工</el-button>
      </div>
    </div>
  </ContentWrap>

  <el-dialog v-model="showReportDialog" title="报工录入" width="40%" :before-close="handleClose">
    <div class="form-container">
      <div class="form-row">
        <span class="form-label">序列号：</span>
        <el-input v-model="form.serialId" disabled class="form-value" />
      </div>

      <div class="form-row">
        <span class="form-label">工单：</span>
        <el-input v-model="form.workOrder" disabled class="form-value" />
      </div>

      <div class="form-row">
        <span class="form-label required">盘长：</span>
        <el-input v-model="form.quantity" placeholder="请输入" class="form-input" >
          <template #append>M</template>
        </el-input>

      </div>

      <div class="form-row">
        <span class="form-label">报工人员：</span>
        <el-input v-model="form.operator" disabled class="form-value" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <WorkStartForm ref="workStartFormRef" :query-params="queryParams" @success="getList" />

  <!-- 列表 -->
  <!--  <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="序列号" align="center" prop="serialNo" />
        <el-table-column label="工单号" align="center" prop="docNo" />
        <el-table-column label="产线" align="center" prop="line" />
        <el-table-column label="设备" align="center" prop="equipment" />
        <el-table-column label="工序" align="center" prop="process" />
        <el-table-column label="数量" align="center" prop="qty" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="操作" align="center" min-width="120px">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['opticore:work-report:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['opticore:work-report:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      &lt;!&ndash; 分页 &ndash;&gt;
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>-->
  <!-- 表单弹窗：添加/修改 -->
  <!--  <WorkReportForm ref="formRef" @success="getList" />-->
</template>

<script setup lang="ts">
import { WorkReportApi, WorkReportVO } from '@/api/opticore/workreport'
import { ProcessInfoApi } from '@/api/opticore/processinfo'
import { Search } from '@element-plus/icons-vue' // 导入图标，这里用Search代替二维码图标
import { getLineDictDataList } from '@/api/system/dict/dict.data'
import { MaterialUsageApi } from '@/api/opticore/materialusage'
import WorkStartForm from './WorkStartForm.vue'
import { watch } from 'vue'
import {DeviceApi} from "@/api/opticore/device";

/** 报工记录 列表 */
defineOptions({ name: 'WorkReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<WorkReportVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const serial = ref('') //物料序列号
const productLineList = ref([])
const deviceList = ref([])
const processList = ref([])
const showReportDialog = ref(false)
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serialNo: "",
  docNo: undefined,
  lineId: undefined,
  equipment: undefined,
  process: undefined,
  processCode: undefined,
  qty: undefined,
  createTime: [],
  productId:undefined
})
const queryFormRef = ref() // 搜索的表单

//报工表单
const form = ref({
  serialId: '',
  workOrder: '', //工单号
  quantity: '',
  operator: JSON.parse(localStorage.getItem('userInfo')).nickname // 默认值
})

const showStartDialog = ref(false)
const mode = ref('report') // 'report' 或 'start'
const workStartFormRef = ref()

const canStart = ref(true)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WorkReportApi.getWorkReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const fetchProductLineList = async () => {
  try {
    const result = await getLineDictDataList();
    productLineList.value = result.map(item => ({
      id: item.id,      // 产线id
      label: item.label // 产线名称
    }));
    console.log("产线数据 productLineList.value:", productLineList.value)
  } finally {
  }
}

const fetchDeviceList = async () => {
  queryParams.pageNo = 1
  queryParams.pageSize = 1000
  const data = await DeviceApi.getDevicePage(queryParams);
  deviceList.value = data.list;
}

const fetchProcessList = async () => {
  try {
    processList.value = await ProcessInfoApi.fetchProcessNameList()
  } finally {
  }
}

/** 报工逻辑 */
const handleReport = async () => {
  if (queryParams.lineId === undefined || queryParams.lineId === null) {
    message.warning('请选择产线')
    return
  }

  if (queryParams.equipment === undefined || queryParams.equipment === null) {
    message.warning('请选择设备')
    return
  }

  if (queryParams.process === undefined || queryParams.process === null) {
    message.warning('请选择工序')
    return
  }

  if (serial.value === '') {
    message.warning('请扫描序列号')
    return
  }
  console.log('报工')
  console.log(serial.value)
  const docNo = await fetchMaterialsInfoBySerialId(serial.value)
  if (!docNo) {
    return
  }
  form.value.serialId = serial.value
  form.value.workOrder = docNo
  //获取工单号
  showReportDialog.value = true
}

const fetchMaterialsInfoBySerialId = async (serialId) => {
  const data = await MaterialUsageApi.getMaterialInfoBySerialNo(serialId)
  if (data == null) {
    message.error(`无效的物料编号: ${serialId}`)
    serial.value = ''
    return
  }
  return data.docNo
}

// 报工逻辑提交
const handleSubmit = async () => {
  const reportVo = reactive({
    serialNo: form.value.serialId,
    docNo: form.value.workOrder,
    lineId: queryParams.lineId,
    equipment: queryParams.equipment,
    process: queryParams.process,
    processCode: queryParams.processCode,
    qty: form.value.quantity,
    updater: form.value.operator
  })
  console.log("提交报工参数",reportVo);
  const data = reportVo as unknown as WorkReportVO
  await WorkReportApi.createWorkReport(data)

  //报工后 更新工单状态完成
  const res=await WorkReportApi.updateWorkReportStatus(data.serialNo, productIdNew.value);
  console.log("报工后 更新工单状态完成",res);

  message.success(t('报工成功'))
  showReportDialog.value = false
  form.value.quantity=""
  // 发送操作成功的事件
  emit('success')


}

const handleClose = (done) => {
  // 可以添加关闭前的确认逻辑
  done()
}

const handleStart = async () => {
  // 检查工序是否有值
  if (!queryParams.process) {
    message.warning('请先扫描正确的序列号获取工序信息')
    return
  }
  console.log("工序值",queryParams.process,queryParams.processCode);

  // 获取选中的产线名称
  const selectedLine = productLineList.value.find(item => item.id === queryParams.lineId)
  const lineName = selectedLine ? selectedLine.label : ''

  // 重新检查是否存在开工记录
  const res = await WorkReportApi.getWorkInfoBySerialNo(serial.value, lineName)
  if (res && res.isWorkInfo) {
    message.warning('存在开工记录')
    return
  }

  // 传递参数，带上产线id和产线名称
  workStartFormRef.value.open({
    ...queryParams,
    lineName,
    processCode:res.processCode
  })
}

/** 初始化 **/
onMounted(() => {
  getList()
  fetchProductLineList()
  fetchDeviceList()
  fetchProcessList()
})


const productIdNew = ref();

// 监听物料序列号变化
watch(serial, async (newVal) => {
  queryParams.serialNo = newVal

  // 新增校验逻辑：检查产线设备是否已填
  if (newVal && (!queryParams.lineId || !queryParams.equipment)) {
    message.warning('请先选择产线和设备')
    serial.value = '' // 清空序列号
    return
  }

  if (newVal) {
    // 获取选中的产线名称
    const selectedLine = productLineList.value.find(item => item.id === queryParams.lineId)
    const lineName = selectedLine ? selectedLine.label : ''

    const res = await WorkReportApi.getWorkInfoBySerialNo(newVal, lineName)
    if (res && res.isWorkInfo) {
      //存在开工记录
      canStart.value = false
      queryParams.process = res && res.workSerial ? res.workSerial : undefined
      queryParams.processCode = res && res.workSerialCode ? res.workSerialCode : undefined
      productIdNew.value = res.productId;
    } else {
      canStart.value = true
      queryParams.process = res && res.workSerial ? res.workSerial : undefined
      queryParams.processCode = res && res.workSerialCode ? res.workSerialCode : undefined
      queryParams.docNo = res?.doc_no || undefined
      queryParams.productId=res.productId || null
      productIdNew.value = res.productId;
    }
    console.log("查看工序",queryParams,res.workSerialCode);
  } else {
    queryParams.process = undefined
    canStart.value = true
  }
})
</script>
<style>
.serial-number {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-top: 50px;  /* 调整上边距 */
  margin-bottom: 40px;
  color: #333;
}

.report-btn-container {
  text-align: center;
  margin-bottom: 30px;  /* 增加底部间距 */
}

.report-btn {
  width: 220px;
  height: 160px;
  font-size: 48px;
}

.serial-input {
  width: 500px; /* 调整宽度 */
  height: 50px; /* 调整高度 */
  font-size: 18px; /* 增大字体 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.form-container {
  padding: 10px 20px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-label {
  width: 80px;
  font-size: 14px;
  color: #606266;
  flex-shrink: 0;
}

.form-value {
  flex-grow: 1;
  height: 40px;
  line-height: 40px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.form-input {
  flex-grow: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-dialog__footer {
  text-align: center;
}
</style>

